const role = require('../models/role')
const role_permission = require('../models/rolePermission')
const admin_role = require('../models/adminRole')

class roleDao {
  // 添加角色
  static async create(v) {
    const res = await role.create({
      name: v.name,
      description: v.description,
      status: 1
    })
    return res
  }
  // 修改角色信息
  static async edit(v) {
    const res = await role.update(v, {
      where: {
        id: v.id
      }
    })
    return res
  }
  // 获取所有角色
  static async getAllRole(v) {
    const res = await role.findAndCountAll({
      limit: v.limit,
      offset: v.offset 
    })
    let result = {}
    result.data = res.rows;
    result.total = res.count;
    return result
  }
  // 分配权限
  static async setRules(v) {
    const res = await role_permission.create({
      rid: v.rid,
      pid: v.pid
    })
    return res
  }
  // 获取权限
  static async getRules(v) {
    const res = await role_permission.findAll({
      rid: v.rid
    })
    return res
  }
  // 删除权限
  static async delRules(v) {
    const res = await role_permission.destroy({
      where: {
        rid: v.rid
      }
    })
    return res
  }
  // 分配角色
  static async setRole(v) {
    const res = await admin_role.create({
      uid: v.uid,
      rid: v.rid
    })
    return res
  }
  // 获取某用户角色id
  static async getRole(v) {
    const res = await admin_role.findOne({
      uid: v
    })
    if(!res){
      return null
    }
    return res.dataValues.rid
  }
}

module.exports = roleDao